package com.example.hrm.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class JwtTokenProvider {

    // 移除从配置文件读取密钥的方式
    // @Value("${jwt.secret}")
    // private String jwtSecret;

    @Value("${jwt.expiration}")
    private long jwtExpirationMs;

    // 使用ThreadLocal存储生成的密钥，确保应用运行期间使用同一密钥
    private static final ThreadLocal<SecretKey> SECRET_KEY_HOLDER = ThreadLocal.withInitial(() -> 
            Keys.secretKeyFor(SignatureAlgorithm.HS512)
    );

    private final Set<String> invalidatedTokens = ConcurrentHashMap.newKeySet();
    // 生成JWT令牌
    public String generateToken(String username, String role) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpirationMs);

        SecretKey key = SECRET_KEY_HOLDER.get();

        return Jwts.builder()
                .setSubject(username)
                .claim("role", role)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
    }

    // 从令牌中获取用户名
    public String getUsernameFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY_HOLDER.get())
                .build()
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    // 验证令牌
    public boolean validateToken(String token) {
        try {
            if (invalidatedTokens.contains( token)){
                return false;
            }
            Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY_HOLDER.get()) // 使用统一密钥
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public void invalidateToken(String token) {
        invalidatedTokens.add(token);
        cleanUpInvalidatedTokens();
    }
    private void cleanUpInvalidatedTokens() {
        invalidatedTokens.removeIf(token-> {
            try {
                Claims claims = Jwts.parserBuilder()
                        .setSigningKey(SECRET_KEY_HOLDER.get())
                        .build()
                        .parseClaimsJws(token)
                        .getBody();
                return claims.getExpiration().before(new Date());
            }catch (Exception e){
                return true;
            }
        });
    }

}